const {
  SystemNotFoundError,
  SystemHasMenuError,
} = require('../../domain/system/error')
const Usecase = require('../../shared/usecase/Usecase')

class DeleteSystem extends Usecase {
  constructor({ systemRepo, currentUser, database }) {
    super(['DeletedSystem'])
    this.systemRepo = systemRepo
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }

  async execute(data) {
    const { DeletedSystem } = this.eventMap
    const system = await this.systemRepo.findById(data, {
      include: ['menuList'],
    })
    if (!system) throw new SystemNotFoundError(data)
    if (system.hasMenu()) throw new SystemHasMenuError(system.name)
    const transaction = await this.sequelize.transaction()
    try {
      await this.systemRepo.remove(system, {
        currentUser: this.currentUser,
        transaction,
      })
      await transaction.commit()
      this.emit(DeletedSystem, system)
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = DeleteSystem
